package com.binarygadget.hatebureader

import java.io.IOException
import java.net.MalformedURLException
import java.util.ArrayList
import java.util.Date
import java.net.{URI, URL}
import java.nio.{ByteBuffer, CharBuffer}
import javax.xml.parsers.ParserConfigurationException
import org.xml.sax.SAXException
import _root_.android.app.Activity
import _root_.android.app.AlertDialog
import _root_.android.app.Dialog
import _root_.android.os.Bundle
import _root_.android.view.LayoutInflater
import _root_.android.view.Menu
import _root_.android.view.View
import _root_.android.view.MenuItem
import _root_.android.widget.AdapterView
import _root_.android.widget.ArrayAdapter
import _root_.android.widget.ListView
import _root_.android.widget.TextView
import _root_.android.widget.AdapterView.OnItemClickListener
import scala.io
import scala.io._


class HatebuReader extends Activity {

  private val ENTRY_DIALOG:Int = 1
  private val MENU_UPDATE:Int = Menu.FIRST

  var blogEntries = new ArrayList[BlogEntry]()
  var aa: ArrayAdapter[BlogEntry] = null
  var blogEntryListView: ListView = null
  var selectedEntry: BlogEntry = null
  
  override def onCreate(icicle:Bundle) {

    super.onCreate(icicle)
    setContentView(List(R.layout.main) first)

    blogEntryListView = findViewById(R.id.blogentryListView).asInstanceOf[ListView]

    blogEntryListView.setOnItemClickListener(new OnItemClickListener() {
    def onItemClick(_av: AdapterView[_], _v: View, _index: Int, _id: Long) {
      selectedEntry = blogEntries.get(_index)
      showDialog(ENTRY_DIALOG)
    }

    })
    aa = new ArrayAdapter[BlogEntry](getApplicationContext(), _root_.android.R.layout.simple_list_item_1, blogEntries)
    blogEntryListView.setAdapter(aa)
    refreshHotEntry()
  }

  private def refreshHotEntry()
  {

    try{
      val src = scala.io.Source.fromURL("http://rss.rssad.jp/rss/itmtop/1.0/topstory.xml","utf-8")
//      val src = scala.io.Source.fromURL(getString(R.string.hatena_feed),"utf-8")
      val cpa = scala.xml.parsing.ConstructingParser.fromSource(src, false) // fromSource initializes automatically
      val ele = cpa.document().docElem
      blogEntries.clear()

      ele match {
	case <rdf:RDF>{therms @ _*}</rdf:RDF> =>
          for (therm @ <item>{_*}</item> <- therms)
            {
	      var title = (therm \ "title").text
	      var link = (therm \ "link").text
	      val entry_ = new BlogEntry(title, link)
	      addNewEntry(entry_)
            }
      }


    } catch {
      case ex: MalformedURLException        => ex.printStackTrace()
      case ex: IOException                  =>  ex.printStackTrace()
      case ex: ParserConfigurationException =>  ex.printStackTrace()
      case ex: SAXException                 =>  ex.printStackTrace()
    } finally {
      
    }
  }

  private def addNewEntry(_entry:BlogEntry) {
    blogEntries.add(_entry)
    aa.notifyDataSetChanged()
  }

  override def onCreateOptionsMenu(menu:Menu): Boolean = {
    super.onCreateOptionsMenu(menu)
    
    menu.add(0, MENU_UPDATE, Menu.NONE, R.string.menu_update)
    
    true
  }

  override def onOptionsItemSelected(item:MenuItem): Boolean = {
    super.onOptionsItemSelected(item)
    
    item.getItemId() match {
      case MENU_UPDATE => {
        refreshHotEntry()
        return true
      }
    }
    false
  }
  
  override def onCreateDialog(id:Int):Dialog = {
    
    id match {
      case ENTRY_DIALOG => {
	var li = LayoutInflater.from(this)
	var entryDetailsView = li.inflate(R.layout.entry_details, null)
      
	var quakeDialog = new AlertDialog.Builder(this)
	quakeDialog.setTitle("")
	quakeDialog.setView(entryDetailsView)
	return quakeDialog.create()
      }
    }

    null
  }

  override def onPrepareDialog(id:Int, dialog:Dialog) {
    id match {
      case ENTRY_DIALOG => {
	var quakeText = selectedEntry.title + "\n" + selectedEntry.link
	var entryDialog = dialog.asInstanceOf[AlertDialog]
	entryDialog.setTitle("")
      
	val tv = entryDialog.findViewById(R.id.entryDetailsTextView).asInstanceOf[TextView]
	if (tv != null) {
          tv.setText(quakeText)
	}
      }
    }
  }

}
